﻿using NLog.Fluent;
using SHDM.Web.DataAccess;
using SHDM.Web.Infrastructure;
using SHDM.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using static SHDM.Web.Models.ModelState;

namespace SHDM.Web.Controllers
{
    
    [Authenticator]
    [RoutePrefix("api/Folder")]
    public class FolderController : ApiBaseController
    {
        readonly List<string> FileASC = new List<string>() { "ASC", "DESC" };
        readonly List<string> FileOrderBy = new List<string>() { "NAME", "SIZE", "LASTUPDATEDATE" };
        /// <summary>
        /// 获取文件夹中所有文件
        /// </summary>
        /// <param name="folderId"></param>
        /// <param name="orderby"></param>
        /// <param name="asc">
        /// 0=正序
        /// 1-倒序
        /// </param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetFolderChildrens")]
        public Result GetFolderChildrens(int folderId, string orderby, string asc, string search, int state)
        {
            StringBuilder cmd = new StringBuilder($"SELECT * FROM SH_FOLDERS_V A WHERE A.STATE={state}");
            orderby = string.Compare(orderby, "FILENAME") == 0 ? "NAME" : orderby;
            if(folderId >= 0)
            {
                cmd.Append($" AND A.PARENTID={folderId}");
            }

            if (this.AccountInfo.Role != sh_users.Roles.Admin)
            {
                var lstDept = sh_dept.GetParents(this.AccountInfo.DeptID);
                cmd.Append($" AND A.DEPTID IN({string.Join(",", lstDept.Select(e => e.ID).ToArray())},0)");
            }

            if (!string.IsNullOrEmpty(orderby) && FileOrderBy.Contains(orderby))
            {
                cmd.Append($" ORDER BY A.{orderby}");
            }
            else
            {
                cmd.Append($" ORDER BY A.NAME");
            }

            if (!string.IsNullOrEmpty(asc) && FileASC.Contains(asc.ToUpper()))
            {
                cmd.Append($" {asc}");
            }
            
                        
            return new Result() { Data = new SHDMEntities().SqlQueryDicReader(cmd.ToString()) };
        }

        [HttpGet]
        [Route("CreateFolder")]
        public Result CreateFolder(int folderId, string folderName,int deptID)
        {
            if (string.IsNullOrEmpty(folderName))
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "请输入文件夹名称" };
            }

            var db = new SHDMEntities();
            if (folderId > 0 && !db.sh_folders.Any(e => e.ID == folderId))
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "当前文件夹不存在" };
            }

            if (db.sh_folders.Any(e => e.Name == folderName && e.ParentID == folderId))
            {
                var lstName = db.sh_folders.Where(e => e.Name.StartsWith(folderName + "(") && e.ParentID==folderId && e.State == FolderState.Active).Select(e => e.Name).ToList();
                if (lstName != null && lstName.Count > 0)
                {                   
                    var i = 1;
                    while (true)
                    {
                        if (!lstName.Contains($"{folderName}({i})"))
                        {
                            folderName = $"{folderName}({i})";
                            break;
                        }
                        i++;
                    }
                }
                else
                {
                    folderName = $"{folderName}(1)";
                }
            }

            var entity = new sh_folders()
            {
                Name = folderName,
                ParentID = (folderId<0?0:folderId),
                DeptID=deptID,
                State= FolderState.Active,
                CreateDate = DateTime.Now,
                CreateBy = this.AccountInfo.ID,
                LastUpdateDate = DateTime.Now,
                LastUpdateBy = this.AccountInfo.ID
            };
            db.sh_folders.Add(entity);
            db.SaveChanges();
            var m = db.SqlQueryDicReader($"SELECT A.*,B.NAME AS DEPTNAME FROM SH_FOLDERS A LEFT JOIN SH_DEPT B ON A.DEPTID=B.ID WHERE A.ID={entity.ID}");
            return new Result() { ErrorMessage = "操作成功", Data = m };

        }

        [HttpPost]
        [Route("RecyclingFolders")]
        public Result RecyclingFolders(List<int> listID)
        {
            var db = new SHDMEntities();
            var lst = db.sh_folders.Where(e => listID.Contains(e.ID) && e.State == FolderState.Active).ToList();
            if (lst != null && lst.Count > 0)
            {
                lst.ForEach(row => {
                    row.State = FileState.Delete;
                    row.LastUpdateBy = this.AccountInfo.ID;
                    row.LastUpdateDate = DateTime.Now;                    
                });                
                db.SaveChanges();
            }
            return new Result() { ErrorMessage = "操作成功" };
        }

        [HttpGet]
        [Route("ModifyFolderName")]
        public Result ModifyFolderName(int id, string folderName)
        {
            var db = new SHDMEntities();            
            var entity = db.sh_folders.FirstOrDefault(e => e.ID == id);
            if (entity == null)
            {
                return new Result() { ErrorCode = 1, ErrorMessage = "文件不存在" };
            }            
            
            if (db.sh_folders.Any(e => e.Name == folderName && e.ID != id && e.ParentID == entity.ParentID))
            {
                var lstName = db.sh_folders.Where(e => e.Name.StartsWith(folderName+"(") && e.ParentID == entity.ParentID).Select(e => e.Name).ToList();
                if (lstName != null && lstName.Count > 0)
                {
                    var j = 1;
                    while (true)
                    {
                        if (!lstName.Contains($"{folderName}("))
                        {
                            folderName = $"{folderName}({j})";
                            break;
                        }
                        j++;
                    }
                }
                else
                {
                    folderName = $"{folderName}(1)";
                }
            }
            entity.Name = folderName;
            entity.LastUpdateDate = DateTime.Now;
            entity.LastUpdateBy = this.AccountInfo.ID;
            db.SaveChanges();
            return new Result() { ErrorMessage = "操作成功", Data = entity };
        }

        [HttpGet]
        [Route("GetParent")]
        public Result GetParent(int id)
        {
            var res = new SHDMEntities().SqlQueryDicReader($"call getFolderParent({id})");
            return new Result() { Data = res };
        }

        [HttpGet]
        [Route("GetFolderDeptChildren")]
        public Result GetFolderDeptChildren(int id)
        {
            var db = new SHDMEntities();
            int deptID = 0;
            if (id > 0)
            {
                var folder = db.sh_folders.FirstOrDefault(e => e.ID == id);
                if (folder == null)
                {
                    return new Result() { ErrorCode = 1, ErrorMessage = "文件夹不存在" };
                }
                deptID = folder.DeptID;
            }
            var lst = db.Database.SqlQuery<sh_dept>($"select * from sh_dept t where FIND_IN_SET(id,queryChildrenDeptInfo({deptID}))").ToList();
            return new Result() { Data=new { depts=lst,deptID= deptID } };
        }
    }
}